<script setup>
import { getStudentDetailApi, getstudentStatusDataApi } from '@/api/job'
import { ref, onMounted, onBeforeUnmount } from 'vue'
import { useRouter } from 'vue-router'
import { addWatermark, removeWatermark } from '@/utils/common/watermark'
import html2canvas from 'html2canvas'
import { ElMessage } from 'element-plus'

const props = defineProps({
  account: {
    type: String,
    default: ''
  },
  name: {
    type: String,
    default: ''
  }
})

const router = useRouter()
// 学生数据
const studentData = ref([])

async function getStudentData() {
  const res = await getStudentDetailApi({ account: props.account })
  console.log(res)
  studentData.value = res.data
}
// 学生状态数据
const studentStatusData = ref([])

async function getstudentStatusData() {
  const res = await getstudentStatusDataApi({ studentAccount: props.account })
  console.log(res)
  studentStatusData.value = res.data
}
getstudentStatusData()
onMounted(() => {
  getStudentData()
  // 添加水印
  addWatermark(`${props.account} ${props.name}`)
})

// 导航回退
function routerBack() {
  router.back()
}

// 添加以下工具函数
function getStatusTime(item) {
  if (item.status === 2) return item.entryTime
  if (item.status === 1) return item.interviewTime
  return item.create_time
}

function getStatusType(status) {
  const types = {
    0: 'info',
    1: 'warning',
    2: 'success',
    3: 'success'
  }
  return types[status] || 'info'
}

function getStatusTagType(status) {
  const types = {
    0: 'info',
    1: 'warning',
    2: 'success',
    3: 'success'
  }
  return types[status] || 'info'
}

function getStatusText(status) {
  const texts = {
    0: '已申请',
    1: '待面试',
    2: '已入职',
    3: '已提交材料'
  }
  return texts[status] || '未知状态'
}

function getInterviewResultType(result) {
  const types = {
    0: 'warning',
    1: 'danger',
    2: 'success'
  }
  return types[result] || 'info'
}

function getInterviewResultText(result) {
  const texts = {
    0: '待面试',
    1: '未通过',
    2: '已通过'
  }
  return texts[result] || '未知'
}

function formatLocation(location) {
  try {
    return JSON.parse(location).join(' ')
  } catch {
    return location || ''
  }
}

// 添加打印图片功能
async function handlePrintImage() {
  try {
    // 获取要截图的DOM元素
    const element = document.querySelector('.student-detail')
    if (!element) {
      ElMessage.error('获取页面元素失败')
      return
    }

    ElMessage.info('正在生成图片，请稍候...')

    // 使用html2canvas截图
    const canvas = await html2canvas(element, {
      useCORS: true, // 允许加载跨域图片
      scale: 2, // 提高图片质量
      backgroundColor: '#ffffff' // 设置白色背景
    })

    // 将canvas转为图片
    const image = canvas.toDataURL('image/png')

    // 创建下载链接
    const link = document.createElement('a')
    link.href = image
    link.download = `学生状态追踪-${props.name}-${new Date().getTime()}.png`

    // 触发下载
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)

    ElMessage.success('图片已成功导出')
  } catch (error) {
    console.error('生成图片失败:', error)
    ElMessage.error('生成图片失败，请重试')
  }
}

// 在组件销毁前移除水印
onBeforeUnmount(() => {
  removeWatermark()
})
</script>

<template>
  <div class="student-detail">
    <div class="header">
      <el-button @click="routerBack" icon="ArrowLeft">返回</el-button>
      <el-button type="primary" @click="handlePrintImage" :icon="Document" class="print-btn">
        导出图片
      </el-button>
      <h2>学生详细信息</h2>
    </div>

    <el-card class="info-card">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="学号">{{ studentData.studentNumber }}</el-descriptions-item>
        <el-descriptions-item label="姓名">{{ studentData.name }}</el-descriptions-item>
        <el-descriptions-item label="班级">{{ studentData.class }}</el-descriptions-item>
        <el-descriptions-item label="性别">{{ studentData.gender }}</el-descriptions-item>
        <el-descriptions-item label="手机号">{{ studentData.phone }}</el-descriptions-item>
        <el-descriptions-item label="学院">{{ studentData.college }}</el-descriptions-item>
        <el-descriptions-item label="专业">{{ studentData.major }}</el-descriptions-item>
        <el-descriptions-item label="实习状态">
          <el-tag :type="studentData.internship ? 'success' : 'info'">
            {{ studentData.internship ? '已实习' : '未实习' }}
          </el-tag>
        </el-descriptions-item>
      </el-descriptions>
    </el-card>

    <!-- 添加状态追踪时间线 -->
    <el-card class="status-card" v-if="studentStatusData.length">
      <template #header>
        <div class="card-header">
          <h3>状态追踪</h3>
        </div>
      </template>

      <el-timeline>
        <el-timeline-item
          v-for="item in studentStatusData"
          :key="item.id"
          :timestamp="getStatusTime(item)"
          :type="getStatusType(item.status)"
        >
          <el-card class="status-item">
            <template #header>
              <div class="status-header">
                <span class="company-name">{{ item.enterpriseName }}</span>
                <el-tag :type="getStatusTagType(item.status)">{{
                  getStatusText(item.status)
                }}</el-tag>
              </div>
            </template>

            <div class="status-content">
              <p><strong>职位：</strong>{{ item.jobName }}</p>

              <template v-if="item.status >= 1">
                <p><strong>面试官：</strong>{{ item.interviewer }}</p>
                <p><strong>面试时间：</strong>{{ item.interviewTime }}</p>
                <p v-if="item.interviewPlace">
                  <strong>面试地点：</strong>{{ formatLocation(item.interviewPlace) }}
                  {{ item.interviewDetailPlace }}
                </p>
                <p v-if="item.interviewresult !== null">
                  <strong>面试结果：</strong>
                  <el-tag :type="getInterviewResultType(item.interviewresult)">
                    {{ getInterviewResultText(item.interviewresult) }}
                  </el-tag>
                </p>
              </template>

              <template v-if="item.status === 2">
                <p>
                  <strong>工作地点：</strong>{{ formatLocation(item.jobLocation) }}
                  {{ item.jobDetailLocation }}
                </p>
                <p><strong>薪资：</strong>{{ item.salary }}</p>
                <p><strong>入职时间：</strong>{{ item.entryTime }}</p>
              </template>
            </div>
          </el-card>
        </el-timeline-item>
      </el-timeline>
    </el-card>
  </div>
</template>

<style lang="scss" scoped>
.student-detail {
  padding: 20px;

  .header {
    display: flex;
    align-items: center;
    margin-bottom: 20px;

    .print-btn {
      margin-left: 10px;
    }

    h2 {
      margin-left: 20px;
      margin-bottom: 0;
    }
  }

  .info-card {
    max-width: 1000px;
    margin: 0 auto;
  }

  .status-card {
    max-width: 1000px;
    margin: 20px auto;
  }

  .card-header {
    h3 {
      margin: 0;
    }
  }

  .status-item {
    .status-header {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .company-name {
        font-weight: bold;
        font-size: 16px;
      }
    }

    .status-content {
      p {
        margin: 8px 0;
      }
    }
  }
}
</style>
